var qr_image = require('qr-image');

module.exports=function(app,request){
    // 发起 POST /api/login 请求完成用户登录，并添加该用户到 req.session.authUser
    app.post('/api/login', function (req, res) {
       request.post(
           {
                url:'http://www.midoogame.com/wapauth/login',
                form:{
                    username:req.body.username,
                    password:req.body.password,
                    fromflag:5
                }
            },
            function(error, response, body){
                const resBody=JSON.parse(body);
                if(!error && response.statusCode == 200 && resBody.sendstatus == 200){
                    req.session.authUser = resBody.data
                    return res.json(resBody.data)
                }
                res.status(401).json({ error: resBody.sendmsg,status:resBody.sendstatus })
            }
        )
    })
  
    // 发起 POST /api/logout 请求注销当前用户，并从 req.session 中移除
    app.post('/api/logout', function (req, res) {
        delete req.session.authUser
        res.json({ msg:'成功退出',status: true })
    })

    app.get('/qrcode',function(req,res){
        //console.log(req.query.url);
        var code = qr_image.image(req.query.url, {type: 'png',margin:1});
        res.setHeader('Content-type', 'image/png');
        code.pipe(res);/**/
    })
    let page=1,id=null;
    app.get('/bbs', (req, res) => {//抓帖子数据
        const num = ++page;
        request.post({
            url: 'http://www.tiboo.cn/pw_ajax.php?action=indexrecommend',
            form: { page: num, lastid: id }
        }, (error, response, body) => {
            if (!error) {
                const resBody=JSON.parse(body)
                id=resBody.lastid
                console.log('id',id);
                res.json(resBody)
            } else {
                console.log('error:', error);
            }
        });
    })
}